package org.rafal.springframework.service.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.rafal.springframework.domain.Text;
import org.rafal.springframework.service.TextService;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("textService")
@Repository
@Transactional
public class TextServiceImpl implements TextService {

	Log logger = LogFactory.getLog(TextServiceImpl.class);

	@PersistenceContext
	private EntityManager em;

	@Transactional(readOnly = true)
	public List<Text> findAll() {
		logger.info("Finding all Text objects.");
		return em.createNamedQuery("text.findAll", Text.class).getResultList();
	}

	@Transactional(readOnly = true)
	public Text findBySubject(String subject) {
		TypedQuery<Text> typedQuery = em.createNamedQuery("text.findBySubject",
				Text.class);
		typedQuery.setParameter("subject", subject);
		logger.info("Returning  Text object with subject name " + subject);
		return typedQuery.getSingleResult();
	}

	public Text save(Text text) {
		if (text.getId() == null) {
			logger.info("Inserted new Text.");
			em.persist(text);
		} else {
			logger.info("Updating Text.");
			em.merge(text);
		}
		return text;
	}

	@Override
	public void delete(Text text) {
		Text deleteText = em.merge(text);
		em.remove(deleteText);
		logger.info("Text with id: " + text.getId() + " deleted successfully.");

	}

}
